package com.software.sqlite.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SocketFactory;

/**
 * 相关链接： JSCH api：http://epaul.github.io/jsch-documentation/javadoc/ Example:
 * http://www.jcraft.com/jsch/examples/
 *
 * @author xxxx
 *
 */
public class JSCHUtils {
    private static JSch jsch = new JSch();

    /**
     * 创建Session，并打开Session连接
     *
     * @param dstIp
     * @param dstPort
     * @param localIp
     * @param localPort
     * @param userName
     * @param password
     * @param timeOut
     * @return
     * @throws JSchException
     */
    public static Session createSession(String dstIp, int dstPort,
                                        final String localIp, final int localPort, String userName,
                                        String password, final int timeOut) throws JSchException {
        //jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

        // A Session represents a connection to a SSH server
        Session session = jsch.getSession(userName, dstIp, dstPort);
        session.setPassword(password);

        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");//To skip host-key check
        session.setConfig(sshConfig);

        // this socket factory is used to create a socket to the target host,
        // and also create the streams of this socket used by us
        session.setSocketFactory(new SocketFactory() {
            @Override
            public OutputStream getOutputStream(Socket socket)
                    throws IOException {
                return socket.getOutputStream();
            }

            @Override
            public InputStream getInputStream(Socket socket) throws IOException {
                return socket.getInputStream();
            }

            @Override
            public Socket createSocket(String host, int port)
                    throws IOException, UnknownHostException {
                Socket socket = new Socket();
                if (localIp != null) {
                    socket.bind(new InetSocketAddress(InetAddress
                            .getByName(localIp), localPort));
                }
                socket.connect(
                        new InetSocketAddress(InetAddress.getByName(host), port),
                        timeOut);
                return socket;
            }
        });

        session.connect(timeOut);
        return session;
    }
}
